import React, { Fragment, useEffect, useReducer } from 'react';
import { Modal, notification, Icon } from 'antd';
import Link from 'umi/link';
import BatchesForm from './components/BatchesForm';
import TableList from './components/TableList';
import { SIZE, PAGE, IconUrl } from '@/utils/constant';
import { batchesList, editBatches, delStudent } from '@/services/api';

interface initial {
  loading: boolean;
  data: [];
  pagination: object;
  searchValue: object;
}

const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: IconUrl, // 在 iconfont.cn 上生成
});

function BatchesList({ id }: any) {
  const initialState: initial = {
    loading: false,
    data: [],
    pagination: {
      showSizeChanger: true,
    },
    searchValue: {
      clase_id: id,
    },
  };

  const reducer = (state: any, { type, payload }: any) => {
    switch (type) {
      case 'OPEN_LOADING':
        return {
          ...state,
          loading: true,
        };
      case 'CLOSED_LOADING':
        return {
          ...state,
          loading: false,
        };
      case 'GET_DATA':
        return {
          ...state,
          data: payload,
        };
      case 'CHANGE_PAGINATION':
        return {
          ...state,
          pagination: payload,
        };
      case 'SEARCH_VALUE':
        return {
          ...state,
          searchValue: payload,
        };
      default:
        return state;
    }
  };
  const [{ loading, data, pagination, searchValue }, dispatch]: any = useReducer(
    reducer,
    initialState,
  );
  const pager = JSON.parse(JSON.stringify(pagination));
  useEffect(() => {
    dispatch({
      type: 'OPEN_LOADING',
    });
    batchesList({ ...searchValue, page: PAGE, size: SIZE })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  }, []);

  const onChange = (changePagination: any) => {
    pager.current = changePagination.current;
    pager.pageSize = changePagination.pageSize;
    dispatch({
      type: 'CHANGE_PAGINATION',
      payload: pager,
    });
    dispatch({
      type: 'OPEN_LOADING',
    });
    batchesList({
      ...searchValue,
      page: changePagination.current,
      size: changePagination.pageSize,
    })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  };

  const columns = [
    {
      title: '学生姓名',
      key: 'student',
      dataIndex: 'student',
      render: (text: any) => <span>{text && text.name}</span>,
    },
    {
      title: '违纪类型',
      key: 'type',
      dataIndex: 'type',
      render: (text: any) => <span>{text && text.title}</span>,
    },
    {
      title: '标题',
      key: 'title',
      dataIndex: 'title',
    },
    {
      title: '内容',
      key: 'content',
      width: '40%',
      dataIndex: 'content',
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      render: (text: any) =>
        text ? (
          <span>
            <MyIcon type="icon-tubiaozhizuo--open" />
            已处理
          </span>
        ) : (
          <span>
            <MyIcon type="icon-tubiaozhizuo--closed" />
            未处理
          </span>
        ),
    },
    {
      title: '创建时间',
      key: 'created_at',
      dataIndex: 'created_at',
    },
    {
      title: '操作',
      width: 200,
      key: 'option',
      valueType: 'option',
      dataIndex: 'id',
      render: (text: any, object: any) => (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          {object.status ? (
            <a
              onClick={() => {
                delete object.teacher;
                delete object.student;
                delete object.type;
                editBatches({ ...object, status: false }).then(() => {
                  notification.success({
                    message: '未处理成功',
                  });

                  dispatch({
                    type: 'OPEN_LOADING',
                  });
                  dispatch({
                    type: 'SEARCH_VALUE',
                    payload: {
                      ...searchValue,
                    },
                  });
                  batchesList({ ...searchValue, page: PAGE, size: SIZE })
                    .then((res: any) => {
                      if (res.status === 'success') {
                        dispatch({
                          type: 'GET_DATA',
                          payload: res.data.data,
                        });
                        dispatch({
                          type: 'CHANGE_PAGINATION',
                          payload: {
                            current: PAGE,
                            pageSize: SIZE,
                            showSizeChanger: true,
                            total: res.data.meta.total,
                          },
                        });
                      }
                      dispatch({
                        type: 'CLOSED_LOADING',
                      });
                    })
                    .catch(() => {
                      dispatch({
                        type: 'CLOSED_LOADING',
                      });
                    });
                });
              }}
            >
              {' '}
              <MyIcon type="icon-tubiaozhizuo--closed" />
              修改为未处理
            </a>
          ) : (
            <a
              onClick={() => {
                delete object.teacher;
                delete object.student;
                delete object.type;
                editBatches({ ...object, status: true }).then(() => {
                  notification.success({
                    message: '已处理成功',
                  });

                  dispatch({
                    type: 'OPEN_LOADING',
                  });
                  dispatch({
                    type: 'SEARCH_VALUE',
                    payload: {
                      ...searchValue,
                    },
                  });
                  batchesList({ ...searchValue, page: PAGE, size: SIZE })
                    .then((res: any) => {
                      if (res.status === 'success') {
                        dispatch({
                          type: 'GET_DATA',
                          payload: res.data.data,
                        });
                        dispatch({
                          type: 'CHANGE_PAGINATION',
                          payload: {
                            current: PAGE,
                            pageSize: SIZE,
                            showSizeChanger: true,
                            total: res.data.meta.total,
                          },
                        });
                      }
                      dispatch({
                        type: 'CLOSED_LOADING',
                      });
                    })
                    .catch(() => {
                      dispatch({
                        type: 'CLOSED_LOADING',
                      });
                    });
                });
              }}
            >
              <MyIcon type="icon-tubiaozhizuo--open" />
              修改为已处理
            </a>
          )}
        </div>
      ),
    },
  ];

  return (
    <Fragment>
      <BatchesForm dispatch={dispatch} searchValue={searchValue} />
      <TableList
        rowKey="id"
        dataSource={data}
        columns={columns}
        loading={loading}
        pagination={pagination}
        onChange={onChange}
      />
    </Fragment>
  );
}

export default BatchesList;
